<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { message } from '@/utils/message'
import { getToken } from '@/utils/auth'
import { downloadFile } from '@/utils/http'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
  },
})
const uploadRef = ref()
const dialogTitle = ref(props.title)
const uploadVisible = ref(false)

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_API_PREFIX + '/system/user/importData',
})
const emit = defineEmits(['update:visible', 'refresh'])

/** 下载模板操作 */
function importTemplate() {
  downloadFile('system/user/importTemplate', {}, `用户导入模板.xlsx`)
}
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, _) => {
  uploadVisible.value = false
  upload.isUploading = false
  uploadRef.value.handleRemove(file)
  message('导入成功', { type: 'success' })
  emit('refresh')
}

const submitForm = () => {
  uploadRef.value.submit()
}

const closeDialog = () => {
  uploadVisible.value = false
}

watch(
  () => uploadVisible.value,
  (val) => {
    emit('update:visible', val)
  }
)

watch(
  () => props.visible,
  (val) => {
    uploadVisible.value = val
  }
)

watch(
  () => props.title,
  (val) => {
    dialogTitle.value = val
  }
)
</script>

<template>
  <el-dialog
    v-model="uploadVisible"
    :title="dialogTitle"
    :width="500"
    draggable
    :before-close="closeDialog"
  >
    <!-- 表单内容 -->
    <el-upload
      ref="uploadRef"
      :limit="1"
      accept=".xlsx, .xls"
      :headers="upload.headers"
      :action="upload.url + '?updateSupport=' + upload.updateSupport"
      :disabled="upload.isUploading"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      drag
    >
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitForm"> 确定 </el-button>
    </template>
  </el-dialog>
</template>
